package org.learn.file;

import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;

public class FileReader_ {
    public static void main(String[] args) {
//单个字符读取文件
        String filePath = "d:\\a.txt";
        FileReader fileReader = null;
        int data = 0;

        //创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            //循环读取，使用read 单个字符读取
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void readFile02() {
//单个字符读取文件
        String filePath = "d:\\a.txt";
        FileReader fileReader = null;

        int redLen = 0;
        char[] buf = new char[8];

        //创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            //循环读取，使用read(buf) 返回的是实际读取到的字符数
            //如果结果返-1，说明到达文件末尾；
            while ((redLen = fileReader.read()) != -1) {
                System.out.print(new String(buf, 0, redLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

